package com.spice.im.gps;

import java.util.ArrayList;












import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



















import me.maxwin.view.XListViewHeader;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.speed.im.login.EncryptionUtil;
import com.spice.im.ContactFrameActivity;
import com.spice.im.R;
import com.spice.im.SpiceApplication;
import com.spice.im.chat.ChatPullRefListActivity;
import com.spice.im.friend.FriendAddIQ;
import com.spice.im.friend.FriendAddIQResponse;
import com.spice.im.friend.FriendAddIQResponseProvider;
import com.spice.im.preference.PreferenceActivity;
import com.spice.im.preference.PreferenceActivity.exPhoneCallListener;
import com.spice.im.ui.IGpsFilterCallback;
import com.spice.im.utils.HeaderLayout;
import com.spice.im.utils.HeaderLayout.HeaderStyle;
import com.spice.im.utils.HeaderLayout.onMiddleImageButtonClickListener;
import com.spice.im.utils.HeaderLayout.onRightImageButtonClickListener;
import com.spice.im.utils.ImageFetcher;
//import com.stb.isharemessage.R;
//import com.stb.isharemessage.service.Contact;
//import com.stb.isharemessage.BeemApplication.MyLocationListener;
import com.stb.isharemessage.service.aidl.IBeemRosterListener;
import com.stb.isharemessage.service.aidl.IChatManager;
import com.stb.isharemessage.service.aidl.IRoster;
import com.stb.isharemessage.service.aidl.IXmppFacade;
//import com.stb.isharemessage.ui.ContactListPullRefActivity.LoadMoreTask;

//import com.stb.isharemessage.ui.ContactListWithPop.exPhoneCallListener;
//import com.stb.isharemessage.ui.ContactListWithPop.exPhoneCallListener;
//import com.bulletnoid.android.widget.StaggeredGridView.StaggeredGridView;
import com.dodola.model.DuitangInfo;
import com.dodowaterfall.widget.FlowView;
//import com.example.android.bitmapfun.util.AsyncTask;
import com.beem.push.utils.AsyncTask;
//import com.example.android.bitmapfun.util.ImageFetcher;
import com.example.android.bitmapfun.util.ObjectCache;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
//import com.handmark.pulltorefresh.library.PullToRefreshStaggeredGridView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.huewu.pla.lib.internal.PLA_AdapterView;
import com.huewu.pla.lib.internal.PLA_ListView;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.IConnectionStatusCallback;
//import com.stb.isharemessage.IGpsFilterCallback;
//import com.stb.isharemessage.BeemApplication.MyLocationListener;
//import com.stb.isharemessage.service.Contact;
//import com.stb.isharemessage.service.GpsInfo;
//import com.stb.isharemessage.service.PresenceAdapter;
import com.stb.isharemessage.service.XmppConnectionAdapter;
//import com.stb.isharemessage.ui.ChatPullRefListActivity.LoadMoreTask;
//import com.stb.isharemessage.ui.list.NearByPopupWindow;
//import com.stb.isharemessage.ui.list.BasePopupWindow.onSubmitClickListener;
//import com.stb.isharemessage.ui.register.FlippingLoadingDialog;
import com.stb.isharemessage.utils.BeemBroadcastReceiver;
import com.stb.isharemessage.utils.BeemConnectivity;
//import com.stb.isharemessage.utils.HeaderLayout;
//import com.stb.isharemessage.utils.SortedList;
//import com.stb.isharemessage.utils.Status;
//import com.stb.isharemessage.utils.TextUtils;
//import com.stb.isharemessage.utils.HeaderLayout.HeaderStyle;
//import com.stb.isharemessage.utils.HeaderLayout.onMiddleImageButtonClickListener;
//import com.stb.isharemessage.utils.HeaderLayout.onRightImageButtonClickListener;

import com.spice.im.ui.BasePopupWindow.onSubmitClickListener;
import com.spice.im.ui.HandyTextView;
















import dalvik.system.VMRuntime;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ext.SatelliteMenu;
import android.view.ext.SatelliteMenuItem;
import android.view.ext.SatelliteMenu.SateliteClickedListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView.RecyclerListener;
import android.widget.PopupWindow.OnDismissListener;

public class GpsSearchResPullRefListActivity extends Activity implements IConnectionStatusCallback,IGpsFilterCallback,OnClickListener{
    private final static float TARGET_HEAP_UTILIZATION = 0.75f;
    private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;
	private PullToRefreshListView ptrlv;
	private static ExecutorService LIMITED_TASK_EXECUTOR;
    static {
      LIMITED_TASK_EXECUTOR = (ExecutorService) Executors.newFixedThreadPool(7); 
    }; 
	private static final Intent SERVICE_INTENT = new Intent();
	static {
		SERVICE_INTENT.setComponent(new ComponentName("com.spice.im", "com.stb.isharemessage.BeemService"));//自身应用pkg名称，非service所在pkg名称
	}
    private static final String TAG = "AdvancedSearchResPullRefListActivity";
//    private final List<String> mListGroup = new ArrayList<String>();/**群组信息*/
//    private final Map<String, List<Contact>> mContactOnGroup = new HashMap<String, List<Contact>>();/**key群组号，value群组用户列表**/
    private final BeemContactListOnClick mOnContactClick = new BeemContactListOnClick();/**单击某联系人，打开chat聊天对话框*/
//    private final BeemContactListOnLongClick mOnContactLongClick = new BeemContactListOnLongClick();
//    private final Handler mHandler = new Handler();/**联系人列表更新处理handler*/
    private final ServiceConnection mServConn = new BeemServiceConnection(this);
//    private final BeemBroadcastReceiver mReceiver = new BeemBroadcastReceiver();//原来的网络状态注释掉
//    private final ComparatorContactListByStatusAndName<Contact> mComparator = new ComparatorContactListByStatusAndName<Contact>();
//    private final ComparatorContactListByStatusAndName<DuitangInfo> mComparator2 = new ComparatorContactListByStatusAndName<DuitangInfo>();
//    private final BeemRosterListener mBeemRosterListener = new BeemRosterListener();
//    private List<Contact> mListContact;
    private List<XGpsInfo> mListGps;
//    private List<Contact> mListContactTemp;
    private List<XGpsInfo> mListGpsTemp;
//    private Contact contact = null;
    private XGpsInfo gpsInfo;
//    private String mSelectedGroup;
//    private IRoster mRoster;
//    public IRoster getMRoster(){
//    	return mRoster;
//    }
    private StaggeredPullRefAdapter mAdapter = null;
    private boolean mBinded = false;
    private IXmppFacade mXmppFacade;
    public IXmppFacade geIXmppFacade(){
    	return mXmppFacade;
    }
    private IChatManager mChatManager;
	private ImageFetcher mImageFetcher;
	private SharedPreferences mSettings;
	private int uListype = 1;
	private int itemWidth;
	private int column_count = 3;// 显示列数 just for image cut
	//0普通图片listview 1瀑布流  2地图模式
	private int itemWidth_listv = 60;
	private int itemHeigth_listv = 60;
	private String roomname;
	List<DuitangInfo> duitangs2 = new ArrayList<DuitangInfo>();
    private int currentPage = 0;
    private int numberresult = 50;
    private static final int HISTORY_MAX_SIZE = 50;//50
    private int pageCount = 0;//总页数
	private int TotalCount;//总记录条数
//    List<Contact> ContactList = null;//special for cache
//    List<String> tmpGroupList = null;//special for cache
//    private Collection<BookmarkedConference> col = null;
	
//	protected FlippingLoadingDialog mLoadingDialog;
	private XListViewHeader xListViewHeader;
	private HeaderLayout mHeaderLayout;
	private View footerView;
	
//    private exPhoneCallListener myPhoneCallListener = null;
//    private TelephonyManager tm = null;
    
    private EditText editInput_search;
    
//	private SatelliteMenu menu;
//	private List<SatelliteMenuItem> items;
//	
//	private View mNetErrorView;
//	private TextView mConnect_status_info;
	private Context mContext;
	
	private String searchkey;
	private String searchtype;
	private String ages;
	private String genders;
	private String distances;
	private String online;
	
	
	private NearByPopupWindow mPopupWindow;
	
//	private SharedPreferences mSettings;
	private String mLogin = "";//just for ObjectCache prefix
	
    //网络状态start
	private View mNetErrorView;
	private TextView mConnect_status_info;
	private ImageView mConnect_status_btn;
    private exPhoneCallListener myPhoneCallListener = null;
    private TelephonyManager tm = null;
    //网络状态end
	
    public void onCreate(Bundle savedInstanceState) {
    	VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION);
    	VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE); //设置最小heap内存为6MB大小。当然对于内存吃紧来说还可以通过手动干涉GC去处理
    	requestWindowFeature(Window.FEATURE_NO_TITLE);
    	super.onCreate(savedInstanceState);
    	mSettings = PreferenceManager.getDefaultSharedPreferences(this);
    	String tmpJid = mSettings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "").trim();
//    	mLogin = StringUtils.parseName(tmpJid);
    	mLogin = tmpJid;
    	
        setContentView(R.layout.activity_gpssearchrespullreflist);
        mContext = this;
        
//	    IntentFilter mFilter = new IntentFilter();
//	    mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // 添加接收网络连接状态改变的Action
//	    registerReceiver(mNetWorkReceiver, mFilter);
        
		mHeaderLayout = (HeaderLayout) findViewById(R.id.login_header);
//		mHeaderLayout.init(HeaderStyle.DEFAULT_TITLE);
//		mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_IMAGEBUTTON);
		mHeaderLayout.init(HeaderStyle.TITLE_CHAT);
		
//		mHeaderLayout.setDefaultTitle("关注周边", null);
//		mHeaderLayout.setTitleRightImageButton("附近", null,
//				R.drawable.return2,
//				new OnRightImageButtonClickListener());
		
		initPopupWindow();
		
		mHeaderLayout.setTitleChat(R.drawable.ic_chat_dis_1,
				R.drawable.bg_chat_dis_active, "附近",
				SpiceApplication.getInstance().mGpsAddr,
				R.drawable.select2,//ic_menu_invite  ic_topbar_profile
				new OnMiddleImageButtonClickListener(),
				R.drawable.return2,
				new OnRightImageButtonClickListener());
		
		
		
		
//        mLoadingDialog = new FlippingLoadingDialog(this, "请求提交中");
        
        xListViewHeader = (XListViewHeader)findViewById(R.id.xlistview_header);
        xListViewHeader.setVisiableHeight(100);
        xListViewHeader.setState(0);
        xListViewHeader.setVisibility(View.VISIBLE);
        
//    	this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CLOSED));//原来的网络状态注释掉
//    	mListContact = new ArrayList<Contact>();
    	mListGps = new ArrayList<XGpsInfo>();
    	
        Intent intent = getIntent(); 
        //0普通图片listview 1瀑布流  2地图模式
        uListype = intent.getIntExtra("uListypefor", (int) 1);  
        roomname = intent.getStringExtra("roomname");
        
        editInput_search = (EditText)findViewById(R.id.editInput_search);
        
        ptrlv = (PullToRefreshListView) findViewById(R.id.ptrlvHeadLineNews);
        
        mAdapter = new StaggeredPullRefAdapter(this,this,uListype);
        
        
	    searchkey = intent.getStringExtra("searchkey");
	    searchtype = intent.getStringExtra("searchtype");
	    ages = intent.getStringExtra("ages");
	    genders = intent.getStringExtra("genders");
	    distances = intent.getStringExtra("distances");
	    online = intent.getStringExtra("online");
	    
    	myheadimg = getIntent().getStringExtra("myheadimg");
    	if(myheadimg==null || myheadimg.equalsIgnoreCase("null"))
    		myheadimg = "";
    	myusername = getIntent().getStringExtra("myusername");
    	if(myusername==null || myusername.equalsIgnoreCase("null"))
    		myusername = "";
        
        
        mImageFetcher = new ImageFetcher(this, 240);
        mImageFetcher.setUListype(uListype);
        mImageFetcher.setLoadingImage(R.drawable.empty_photo);
        
        itemWidth = this.getWindowManager().getDefaultDisplay().getWidth() / column_count;// 根据屏幕大小计算每列宽度

//        ptrlv.setOnItemClickListener(mOnContactClick);/**单击用户，打开聊天界面*/
//        ptrlv.setOnItemLongClickListener(mOnContactLongClick);/**长按用户*/
//        ptrlv.setOnClickListener();
        ptrlv.setOnItemClickListener(mOnContactClick);
//        ptrlv.setOnLongClickListener(mOnContactLongClick);
        ptrlv.setMode(Mode.BOTH);
        ptrlv.setOnRefreshListener(new MyOnRefreshListener2());
//        ptrlv.getRefreshableView().setRecyclerListener();
        ptrlv.setAdapter(mAdapter);
        
        editInput_search.addTextChangedListener(new watcher());
        
        
        
        //网络状态start
        mNetErrorView = findViewById(R.id.net_status_bar_top);
        mConnect_status_info = (TextView)mNetErrorView.findViewById(R.id.net_status_bar_info_top2);
        mConnect_status_btn = (ImageView)mNetErrorView.findViewById(R.id.net_status_bar_btn);
        mConnect_status_btn.setOnClickListener(this);
        
	    IntentFilter mFilter = new IntentFilter();
	    mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // 添加接收网络连接状态改变的Action
	    registerReceiver(mNetWorkReceiver, mFilter);
        /* 添加自己实现的PhoneStateListener */
        myPhoneCallListener = new exPhoneCallListener();
       
       /* 取得电话服务 */
        tm =(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
       
        /* 注册电话通信Listener */
        tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_CALL_STATE);
	    //网络状态end
        
        
		// 获取当前用户位置
		mLocationClient = new LocationClient(this.getApplicationContext());
		mMyLocationListener = new MyLocationListener();
		mLocationClient.registerLocationListener(mMyLocationListener);
//		mGeofenceClient = new GeofenceClient(getApplicationContext());
		InitLocation();
		
		/**加载前先显示缓存数据start*/
		errorType = 5;
		preLoad();
		if(mListGpsTemp!=null && mListGpsTemp.size()!=0){
			buildContactList();
			mType = 0;
			ptrlv.onRefreshComplete();
		}
		/**加载前先显示缓存数据end*/
		
//		showLoadingDialog("正在定位,请稍候...");
		xListViewHeader.setShowText("正在定位,请稍候...");
		xListViewHeader.setVisibility(View.VISIBLE);
		xListViewHeader.setState(2);
		
		mLocationClient.start();
		if (mLocationClient != null && mLocationClient.isStarted())
		mLocationClient.requestOfflineLocation();
		System.out.println("开始获取");
      
        BeemApplication.getInstance().addActivity(this);
    }
    
	public void onClick(View v) {
		switch (v.getId()) {
		//网络设置
        case R.id.net_status_bar_btn:
			setNetworkMethod(this);
			break;
		}
	}
	private void startLocate() {

		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
//				showLoadingDialog("正在定位,请稍候...");
				xListViewHeader.setShowText("正在定位,请稍候...");
				xListViewHeader.setVisibility(View.VISIBLE);
				xListViewHeader.setState(2);
			}

			@Override
			protected Boolean doInBackground(Void... params) {
//				initContactList();
//				mLocationClient.start();
//				if (mLocationClient != null && mLocationClient.isStarted())
//				mLocationClient.requestOfflineLocation();
				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
//				dismissLoadingDialog();
				xListViewHeader.setState(0);
				xListViewHeader.setVisibility(View.GONE);
				if (!result) {
					showCustomToast("定位失败...");
//					mHandler2.sendEmptyMessage(3);
				} else {
//					mHandler2.sendEmptyMessage(0);
				}
//				ptrstgv.getRefreshableView().hideFooterView();
			}

		});
	}
    
    
    class watcher implements TextWatcher{

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub    
            
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
//            // TODO Auto-generated method stub
//            String aa = s.toString();
//            Pattern p = Pattern.compile(aa);
//            LinkedList<DuitangInfo> mInfos = new LinkedList<DuitangInfo>();        
//            for(int i=0;i<mAdapter.getCount();i++){
////                People pp = people.get(i);
//            	DuitangInfo duitangInfo = (DuitangInfo)mAdapter.getItem(i);
//	            Matcher matcher = p.matcher(duitangInfo.getName()+duitangInfo.getKey());
//	            if(matcher.find()){
//	            	mInfos.add(duitangInfo);
//	            }
//            }
//            
////            mAdapter = new Adapter(getApplicationContext(), we);
//            mAdapter.addItemTop(mInfos);
//            ptrlv.setAdapter(mAdapter);
        	mAdapter.getFilter().filter(s.toString());
        }
        
    }
    private int mType = 0;//1 pulldown 2 pullup
    
	class MyOnRefreshListener2 implements OnRefreshListener2<ListView> {

//		private PullToRefreshListView mPtflv;

		public MyOnRefreshListener2() {
//			this.mPtflv = ptflv;
		}

		@Override
		public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
			// 下拉刷新
			String label = DateUtils.formatDateTime(getApplicationContext(),
					System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
							| DateUtils.FORMAT_SHOW_DATE
							| DateUtils.FORMAT_ABBREV_ALL);

			refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
//			if(currentPage == pageCount){
////				showCustomToast("已达顶端!");
//				mHandler2.sendEmptyMessage(1);
//			}
//			else if(currentPage < pageCount){
//			    ++currentPage;	
//			//mRoster = mXmppFacade.getRosterWithIndexNumber(currentPage*numberresult, numberresult);//0,50
//			mType = 1;
//			new LoadMoreTask().execute();
//			}else//up and down临界状态:如已经到底端了，此时下拉currentPage == 0
//				mHandler2.sendEmptyMessage(1);
			
			if(currentPage>0){
				--currentPage;
//			    addNewMessage(currentPage);
			mType = 2;
//			new LoadMoreTask().execute();
			flag = false;
			LoadMore();
			}
			else if(currentPage == 0){
//				showCustomToast("已达底端!");
				mHandler2.sendEmptyMessage(1);
			}
		}

		@Override
		public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
			// 上拉加载
//			if(currentPage>0){
//				--currentPage;
////			    addNewMessage(currentPage);
//			mType = 2;
//			new LoadMoreTask().execute();
//			}
//			else if(currentPage == 0){
////				showCustomToast("已达底端!");
//				mHandler2.sendEmptyMessage(2);
//			}
			
			if(currentPage == pageCount){
//				showCustomToast("已达顶端!");
				mHandler2.sendEmptyMessage(2);
			}
			else if(currentPage < pageCount){
			    ++currentPage;	
			//mRoster = mXmppFacade.getRosterWithIndexNumber(currentPage*numberresult, numberresult);//0,50
			mType = 1;
//			new LoadMoreTask().execute();
			flag = false;
			LoadMore();
			}else//up and down临界状态:如已经到底端了，此时下拉currentPage == 0
				mHandler2.sendEmptyMessage(2);
		}

	}
//    public class LoadMoreTask extends AsyncTask<Void, Void, Boolean> {
////    	private PullToRefreshListView mPtrlv;
//		public LoadMoreTask() {
////			this.mPtrlv = ptrlv;
//		}
//        @Override
//        protected void onPreExecute() {
//            super.onPreExecute();
////            showLoadingDialog("正在加载,请稍后...");
//        }
//
//        @Override
//        protected Boolean doInBackground(Void... params) {
////            try {
////                Thread.sleep(1000);
////            } catch (InterruptedException e) {
////            }
//        	initContactList();
//            return true;
//        }
//
//        @Override
//        protected void onPostExecute(Boolean result) {
////            mAdapter.getMoreItem();
////            mAdapter.notifyDataSetChanged();
////            ptrstgv.getRefreshableView().hideFooterView();
//            super.onPostExecute(result);
////            dismissLoadingDialog();
////            mAdapter.notifyDataSetChanged();
////            mPtrlv.onRefreshComplete();
//			if (!result) {
//				showCustomToast("数据加载失败...");
//				mHandler2.sendEmptyMessage(3);
//			} else {
//				mHandler2.sendEmptyMessage(0);
//			}
//        }
//
//    }
	private boolean flag = false;
	public void LoadMore(){
		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				if(flag){
//				showLoadingDialog("正在加载,请稍后...");
					xListViewHeader.setShowText("正在加载,请稍候...");
					xListViewHeader.setVisibility(View.VISIBLE);
					xListViewHeader.setState(2);
				}	
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				initContactList();
				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
//				dismissLoadingDialog();
				xListViewHeader.setState(0);
				xListViewHeader.setVisibility(View.GONE);
				
				if (!result) {
					showCustomToast("数据加载失败...");
					mHandler2.sendEmptyMessage(3);
				} else {
					mHandler2.sendEmptyMessage(0);
				}
//				ptrstgv.getRefreshableView().hideFooterView();
			}

		});
	}
    
    @Override
    protected void onResume() {
		super.onResume();
		if (!mBinded){
		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);	    
		}
		if (mBinded){
	        Intent intent = getIntent(); 
	        //0普通图片listview 1瀑布流  2地图模式
	        uListype = intent.getIntExtra("uListypefor", (int) 1);  
	        roomname = intent.getStringExtra("roomname");
	        
		    searchkey = intent.getStringExtra("searchkey");
		    searchtype = intent.getStringExtra("searchtype");
		    ages = intent.getStringExtra("ages");
		    genders = intent.getStringExtra("genders");
		    distances = intent.getStringExtra("distances");
		    online = intent.getStringExtra("online");
		    
	    	myheadimg = getIntent().getStringExtra("myheadimg");
	    	if(myheadimg==null || myheadimg.equalsIgnoreCase("null"))
	    		myheadimg = "";
	    	myusername = getIntent().getStringExtra("myusername");
	    	if(myusername==null || myusername.equalsIgnoreCase("null"))
	    		myusername = "";
	    	
	        Log.e("================20130804uListype resume1================", "++++++++++++++ContactlistWithPop uListype="+uListype);

	        mImageFetcher.setUListype(uListype);
	        mImageFetcher.setExitTasksEarly(false);

            mAdapter.setListype(uListype);
		}
    }

    //SingleTask用此方法处理传过来的参数
    @Override
    protected void onNewIntent(Intent intent) {
            super.onNewIntent(intent);
//            int value = intent.getIntExtra(key, -1);
            uListype = intent.getIntExtra("uListypefor", (int) 1); 
            roomname = intent.getStringExtra("roomname");
            mAdapter.setListype(uListype);

	        mImageFetcher.setUListype(uListype);
	        mImageFetcher.setExitTasksEarly(false);
            Log.e("================20130804uListype resume2================", "++++++++++++++ContactlistWithPop uListype="+uListype);
    }
    
    
    @Override
    protected void onStart() {
		super.onStart();
    }
    /**
     * {@inheritDoc}
     */
    @Override
    protected void onPause() {
		super.onPause();
		mImageFetcher.setExitTasksEarly(true);
		
    }

    @Override
    protected void onDestroy() {
		super.onDestroy();
//		getApplicationContext().unbindService(mServConn);
		if(mPopupWindow!=null){
			mPopupWindow.unRegisterGpsFilterCallback();
			mPopupWindow = null;
		}
	    try{//网络状态相关
		    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
		    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
	    }catch (RemoteException e) {
	    	e.printStackTrace();
	    }
		mLocationClient.stop();
		mImageFetcher.onCancel();
		clearAsyncTask();
		//网络状态start
		unregisterReceiver(mNetWorkReceiver); // 删除广播
		if(tm!=null){
			tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_NONE);//取消监听即可
			tm = null;
		}
		if(myPhoneCallListener!=null)
			myPhoneCallListener = null;
		//网络状态end
//		loadingView.isStop = true;
		if (mBinded) {
			getApplicationContext().unbindService(mServConn);
		    mBinded = false;
		}
		mXmppFacade = null;
//		this.unregisterReceiver(mReceiver);
		Log.e(TAG, "onDestroy activity");
    }
    
    /**
     * 显示模板*/
    public class StaggeredPullRefAdapter extends BaseAdapter implements Filterable,RecyclerListener{
    	private GpsSearchResPullRefListActivity mActivity;
        private Context mContext;
        private LinkedList<DuitangInfo> mInfos;//ArrayList
        private int Listype = 1;//0普通图片listview 1瀑布流  2地图模式
        
        private LinkedList<DuitangInfo> mOriginalValues;
        private final Object mLock = new Object();
        private MyFilter myFilter;
        
        public void setListype(int Listype){
        	this.Listype = Listype;
        }

        public StaggeredPullRefAdapter(Context context,GpsSearchResPullRefListActivity Activity,int uListype) {
//        	super();
            mContext = context;
            mActivity = Activity;
            mInfos = new LinkedList<DuitangInfo>();
            Listype = uListype;
            
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder;
            DuitangInfo duitangInfo = mInfos.get(position);

            if (convertView == null) {
                LayoutInflater layoutInflator = LayoutInflater.from(parent.getContext());
//                if(Listype == 0)
                convertView = layoutInflator.inflate(R.layout.listitem_gpsuser, null);
//              else if(Listype == 1)
//            	convertView = layoutInflator.inflate(R.layout.listitem_usersingle, null);
//            	  convertView = layoutInflator.inflate(R.layout.cell_stgv, null);
                holder = new ViewHolder();
//                holder.imageView = (ScaleImageView) convertView.findViewById(R.id.news_pic);
                holder.imageView = (FlowView)convertView.findViewById(R.id.news_pic);
//                holder.contentView = (TextView) convertView.findViewById(R.id.news_title);
                holder.contentView = (HandyTextView) convertView.findViewById(R.id.user_item_htv_name);
//                holder.user_item_detail = (LinearLayout)convertView.findViewById(R.id.user_item_detail);
                
                holder.user_item_layout_gender = (LinearLayout)convertView.findViewById(R.id.user_item_layout_gender);
                holder.user_item_iv_gender = (ImageView)convertView.findViewById(R.id.user_item_iv_gender);
                holder.user_item_htv_age = (HandyTextView)convertView.findViewById(R.id.user_item_htv_age);
                
                holder.user_item_htv_account = (HandyTextView)convertView.findViewById(R.id.user_item_htv_account);//帐号
                
                holder.user_item_layout_location = (LinearLayout)convertView.findViewById(R.id.user_item_layout_location);
                holder.user_item_htv_distance = (HandyTextView)convertView.findViewById(R.id.user_item_htv_distance);
                holder.user_item_htv_time = (HandyTextView)convertView.findViewById(R.id.user_item_htv_time);
                
                holder.user_item_htv_sign = (HandyTextView)convertView.findViewById(R.id.user_item_htv_sign);//个性签名
                convertView.setTag(holder);
            }else

            holder = (ViewHolder) convertView.getTag();
//            holder.imageView.setImageWidth(duitangInfo.getWidth());
//            holder.imageView.setImageHeight(duitangInfo.getHeight());
            holder.imageView.setItemWidth(duitangInfo.getWidth());
            holder.contentView.setText(duitangInfo.getMsg());
            holder.imageView.set_url(duitangInfo.getKey());//contact.getJIDWithRes()
            holder.imageView.set_roomname(roomname);
            holder.imageView.setName(duitangInfo.getName());
            holder.imageView.setMActivity(mActivity);
            holder.imageView.setHeadimg(duitangInfo.getIsrc());
            holder.imageView.setMyheadimg(myheadimg);
            //20141220 added by allen start
            holder.imageView.setGender(duitangInfo.getGender());//20141220 added by allen start
            holder.imageView.setBirthday(duitangInfo.getBirthday());
            holder.imageView.setSign(duitangInfo.getSign());
            //20141220 added by allen end
            holder.user_item_htv_account.setText(StringUtils.parseName(duitangInfo.getKey()));
            holder.user_item_htv_sign.setText(duitangInfo.getSign());
            if(duitangInfo.getGender()!=null
            		&& !duitangInfo.getGender().equalsIgnoreCase("null")
            		&& duitangInfo.getGender().length()!=0){
            	if(duitangInfo.getGender().equals("1")){//1男，2女
            		holder.user_item_layout_gender.setBackgroundResource(R.drawable.bg_gender_male);
            		holder.user_item_iv_gender.setImageResource(R.drawable.ic_user_male);
            	}else{
            		holder.user_item_layout_gender.setBackgroundResource(R.drawable.bg_gender_famal);
            		holder.user_item_iv_gender.setImageResource(R.drawable.ic_user_famale);
            	}
            }
            int age = 0;
            if(duitangInfo.getBirthday()!=null
            		&& !duitangInfo.getBirthday().equalsIgnoreCase("null")
            		&& duitangInfo.getBirthday().length()!=0){
            	String[] yyyymmdd = duitangInfo.getBirthday().split("-");
            	try{
            		age = com.spice.im.utils.TextUtils.getAge(Integer.parseInt(yyyymmdd[0]),
            				Integer.parseInt(yyyymmdd[1]),
            				Integer.parseInt(yyyymmdd[2]));
            	}catch(Exception e){
            		age = 0;
            	}
            	holder.user_item_htv_age.setText(age+"");
            }
            holder.user_item_htv_distance.setText(duitangInfo.getMdistance());
            holder.user_item_htv_time.setText(duitangInfo.getTime());
            
//            mImageFetcher.loadImage(duitangInfo.getIsrc(), holder.imageView);
//            showCustomToast("222duitangInfo.getIsrc()="+duitangInfo.getIsrc());
            ImageLoader.getInstance().displayImage(duitangInfo.getIsrc(), holder.imageView ,SpiceApplication.getInstance().options);

            holder.contentView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                }
            });
            
//            holder.user_item_detail.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                }
//            });
            
//            Log.e("================20130801getView()================", "++++++++++++++getView()="+duitangInfo.getMsg()+";"+duitangInfo.getWidth()+";"+duitangInfo.getIsrc()+"+++++++++++++");
            return convertView;
        }
        /**
        249	     * 当列表单元滚动到可是区域外时清除掉已记录的图片视图
        250	     *
        251	     * @param view
        252	     */
        @Override
        public void onMovedToScrapHeap(View view) {
            ViewHolder holder = (ViewHolder) view.getTag();
//        	this.imageViews.remove(holder.avatar);
//        	this.imageViews.remove(holder.picPhoto);
            
            holder.imageView.recycle();
            holder.imageView = null;
            
        }
        class ViewHolder {
//            ScaleImageView imageView;
        	FlowView imageView;
//            TextView contentView;
            HandyTextView contentView;//昵称
//            LinearLayout user_item_detail;
            
            
            LinearLayout user_item_layout_gender;//20140731 added 
            ImageView user_item_iv_gender;//性别
            HandyTextView user_item_htv_age;//年龄
            
            HandyTextView user_item_htv_account;//帐号
            
            LinearLayout user_item_layout_location;
            HandyTextView user_item_htv_distance;//距离
            HandyTextView user_item_htv_time;//最近登录时间
            HandyTextView user_item_htv_sign;//个性签名
            
            
        }

        @Override
        public int getCount() {
            return mInfos.size();
        }

        @Override
        public Object getItem(int arg0) {
            return mInfos.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return 0;
        }

        public void addItemLast(List<DuitangInfo> datas) {
        	if(datas!=null){
//            mInfos.addAll(datas);
        		mInfos.clear();
            	for (DuitangInfo info : datas) {
//                    if(!mInfos.contains(info))
//            		if(!contains(info.getKey()))
//            		mInfos.addLast(info);
//            		
//            		if(mInfos.size()>=HISTORY_MAX_SIZE){//仅缓存50条记录
//            			mInfos.removeFirst();
//            		}
//            		mInfos.addLast(info);
            		mInfos.add(info);
                }
//            	new SortedList<DuitangInfo>(mInfos, mComparator2);
        	}
        }

        public void addItemTop(List<DuitangInfo> datas) {
            if(datas!=null){
            	mInfos.clear();
	        	for (DuitangInfo info : datas) {
	//                if(!mInfos.contains(info))
	//        		if(!contains(info.getKey()))
	//        		mInfos.addFirst(info);
//	        		if(mInfos.size()>=HISTORY_MAX_SIZE){
//	        			mInfos.removeLast();
//	        		}
//	        		mInfos.addFirst(info);
	        		mInfos.add(info);
	            }
	//            new SortedList<DuitangInfo>(mInfos, mComparator2);
            }
        }
        public void updateItem(List<DuitangInfo> datas){
        	int index = 0;
        	DuitangInfo di = null;
            if(datas!=null)
            	for (DuitangInfo info : datas) {
//                    if(!mInfos.contains(info))
            		di = containsDuitangInfo(info.getKey());
            		if(di!=null){
            			index = mInfos.indexOf(di);
            			mInfos.remove(di);
//            		    mInfos.addFirst(info);
            		    mInfos.add(index, info);
            		    break;
            		}
                }
        }
        public boolean contains(String key){
//        	for(int i=0;i<mInfos.size();i++){
        		Iterator<DuitangInfo> it = mInfos.iterator();
        		DuitangInfo di;
        		while(it.hasNext()){
        			di = it.next();
        		    if(di.getKey().equals(key))
        			return true;
        		}
//        	}
        	return false;
        }
        public DuitangInfo containsDuitangInfo(String key){
//        	for(int i=0;i<mInfos.size();i++){
        		Iterator<DuitangInfo> it = mInfos.iterator();
        		DuitangInfo di = null;
        		while(it.hasNext()){
        			di = it.next();
        		    if(di.getKey().equals(key))
        			return di;
        		}
//        	}
        	return null;
        }
        @Override
        public Filter getFilter() {
           if (myFilter == null) {
              myFilter = new MyFilter();
           }
           return myFilter;
        }
        
        class MyFilter extends Filter {
        	 
            @Override
            protected FilterResults performFiltering(CharSequence prefix) {
               // 持有过滤操作完成之后的数据。该数据包括过滤操作之后的数据的值以及数量。 count:数量 values包含过滤操作之后的数据的值
               FilterResults results = new FilterResults();
       
               if (mOriginalValues == null) {
                  synchronized (mLock) {
                      // 将list的用户 集合转换给这个原始数据的ArrayList
                      mOriginalValues = mInfos;
                  }
               }
               if (prefix == null || prefix.length() == 0) {
                  synchronized (mLock) {
                	  LinkedList<DuitangInfo> list = mOriginalValues;
                      results.values = list;
                      results.count = list.size();
                  }
               } else {
                  // 做正式的筛选
                  String prefixString = prefix.toString().toLowerCase();
                  Pattern p = Pattern.compile(prefixString);
                  // 声明一个临时的集合对象 将原始数据赋给这个临时变量
                  final LinkedList<DuitangInfo> values = mOriginalValues;
       
                  final int count = values.size();
       
                  // 新的集合对象
                  final LinkedList<DuitangInfo> newValues = new LinkedList<DuitangInfo>();
       
                  for (int i = 0; i < values.size(); i++) {
                      // 如果姓名的前缀相符或者电话相符就添加到新的集合
                      final DuitangInfo info = (DuitangInfo) values.get(i);
       
//                      Log.i("coder", "PinyinUtils.getAlpha(value.getUsername())"
//                            + PinyinUtils.getAlpha(value.getUsername()));
//                      if (PinyinUtils.getAlpha(value.getUsername()).startsWith(
//                            prefixString)
//                            || value.getPhonenum().startsWith(prefixString)||value.getUsername().startsWith(prefixString)) {
//       
//                         newValues.add(info);
//                      }
	      	            Matcher matcher = p.matcher(info.getName()+info.getKey());
	    	            if(matcher.find()){
	    	            	newValues.add(info);
	    	            }
                  }
                  // 然后将这个新的集合数据赋给FilterResults对象
                  results.values = newValues;
                  results.count = newValues.size();
               }
       
               return results;
            }
       
            @Override
            protected void publishResults(CharSequence constraint,
                  FilterResults results) {
               // 重新将与适配器相关联的List重赋值一下
            	mInfos = (LinkedList<DuitangInfo>) results.values;
            	mListGps = convertDuitangInfos2ListContact(mInfos);
               if (results.count > 0) {
                  notifyDataSetChanged();
               } else {
                  notifyDataSetInvalidated();
               }
            }
       
         }
    }
    
    /**
     * Event simple click on item of the contact list.
     * 单击某联系人，打开chat聊天对话框
     */
//    private class BeemContactListOnClick implements PLA_ListView.OnItemClickListener {
    private class BeemContactListOnClick implements OnItemClickListener {
		/**
		 * Constructor.
		 */
		public BeemContactListOnClick( ) {
		}
		/**
		 * {@inheritDoc}
		 */
		@Override
		public void onItemClick(AdapterView<?> arg0, View v, int pos, long lpos) {
		    XGpsInfo c = mListGps.get(pos-1);//pos-1
		    Intent i = new Intent(GpsSearchResPullRefListActivity.this,ChatPullRefListActivity.class);
//		    i.setData(c.toUri());
//            if(c.getEmail()!=null 
//            		&& c.getEmail().length()!=0 
//            		&& !c.getEmail().equalsIgnoreCase("null")
//            		&& (
//            				c.getEmail().toLowerCase().endsWith(".jpg")
//            				|| c.getEmail().toLowerCase().endsWith(".png")
//            				|| c.getEmail().toLowerCase().endsWith(".bmp")
//            				|| c.getEmail().toLowerCase().endsWith(".gif")
//            			))
//            	i.putExtra("headimg", XmppConnectionAdapter.downloadPrefix+StringUtils.parseName(c.getJID())+"/"+"thumbnail_"+c.getEmail());
//            i.putExtra("myheadimg", myheadimg);
//            i.putExtra("myusername",myusername);
		    i.putExtra("jid", c.getUid()+"@0");
            startActivity(i);
		}
    }

//    /**
//     * Comparator Contact by status and name.
//     * 根据联系人在线状态及用户名排序
//     */
//    private static class ComparatorContactListByStatusAndName<T> implements Comparator<T> {
//		/**
//		 * Constructor.
//		 */
//		public ComparatorContactListByStatusAndName() {
//		}
//	
//		@Override
//		public int compare(T c1, T c2) {
//		    if (((Contact) c1).getStatus() < ((Contact) c2).getStatus()) {
//			return 1;
//		    } else if (((Contact) c1).getStatus() > ((Contact) c2).getStatus()) {
//			return -1;
//		    } else
//			return ((Contact) c1).getName().compareToIgnoreCase(((Contact) c2).getName());
//		}
//    }
    private String myheadimg = "";
    private String myheadimgtemp = "";
    private String myusername = "";
    /**
     * The service connection used to connect to the Beem service.
     */
    private class BeemServiceConnection implements ServiceConnection {
    	private Context mContext;
		/**
		 * Constructor.
		 */
		public BeemServiceConnection(Context context) {
			mContext = context;
		}
	
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    if(mXmppFacade!=null){
		    	mBinded = true;//20130804 added by allen
		    	try{
		    		mXmppFacade.getXmppConnectionAdapter().registerConnectionStatusCallback(GpsSearchResPullRefListActivity.this);//网络状态相关
		    	}catch(Exception e){}
		    }
//		    ptrstgv.getRefreshableView().setFooterView(footerView);
//		    getContactList();
//		    startLocate();
//		    initContactList();
//		    buildContactList(group);
//		    if(mXmppFacade!=null)
//		    	try{
//			    	if (mXmppFacade.getXmppConnectionAdapter()!=null){
//			    		myheadimgtemp = mXmppFacade.getXmppConnectionAdapter().getUserInfo().getAvatarId();
//	                    if(myheadimgtemp!=null 
//	                    		&& myheadimgtemp.length()!=0 
//	                    		&& !myheadimgtemp.equalsIgnoreCase("null")
//	                    		&& (
//	                    				myheadimgtemp.toLowerCase().endsWith(".jpg")
//	                    				|| myheadimgtemp.toLowerCase().endsWith(".png")
//	                    				|| myheadimgtemp.toLowerCase().endsWith(".bmp")
//	                    				|| myheadimgtemp.toLowerCase().endsWith(".gif")
//	                    			))
//	                    	myheadimg = XmppConnectionAdapter.downloadPrefix+StringUtils.parseName(mXmppFacade.getXmppConnectionAdapter().getUserInfo().getJid())+"/"+"thumbnail_"+myheadimgtemp;
////	    	    		List<Contact> mListTemp = mXmppFacade.findSpecialUser(StringUtils.parseName(mXmppFacade.getUserInfo().getJid()));
////	    	    		if(mListTemp!=null && mListTemp.size()!=0){
////	    	        		for (int i = 0; i < mListTemp.size(); i++) {
////	    	        			contact = (Contact)mListTemp.get(i);
////	    	        			myusername = contact.getName();
////	    	        		}
////	    	    		}
////	    	    		if(mListTemp!=null){
////	    	    			mListTemp.clear();
////	    	    			mListTemp = null;
////	    	    		}
//			    	}
//		    	}catch(RemoteException e){
//		    		e.printStackTrace();
//		    	}catch(Exception e){
//		    		e.printStackTrace();
//		    	}
		}
		@Override
		public void onServiceDisconnected(ComponentName name) {
			 try{//网络状态相关
				    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
				    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
			    }catch (RemoteException e) {
			    	e.printStackTrace();
			    }
		    mXmppFacade = null;
		    mChatManager = null;
		    if(mListGpsTemp!=null)
		    	mListGpsTemp.clear();
		    mListGps.clear();
		    mBinded = false;
		}
    }
    private String group = "";
	Handler mHandler2 = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				buildContactList();//group
				mType = 0;
				ptrlv.onRefreshComplete();
				
				xListViewHeader.setState(0);
				xListViewHeader.setVisibility(View.GONE);
				break;

			case 1:
				mType = 0;
				ptrlv.onRefreshComplete();
				showCustomToast("已达顶端!");
				break;
			case 2:
				mType = 0;
				ptrlv.onRefreshComplete();
				showCustomToast("已达底端!");
				break;
			case 8://定位成功
				mLocationClient.stop();
				mHeaderLayout.setDefaultTitle("附近", mGpsAddr);
				
				xListViewHeader.setState(0);//fix
				xListViewHeader.setVisibility(View.GONE);
				
				getContactList();
				break;
			case 9://定位失败
				mLocationClient.stop();
				mHeaderLayout.setDefaultTitle("附近", mGpsAddr);
//				getContactList();
				mType = 0;
				ptrlv.onRefreshComplete();
				
				xListViewHeader.setState(0);
				xListViewHeader.setVisibility(View.GONE);
				break;
			case 10:
//				showCustomToast("GenderSelect="+mGenderSelect+";AgeSelect="+mAgeSelect+";TimeSelect="+mTimeSelect);
				//是否重新定位
//				xListViewHeader.setShowText("正在定位,请稍候...");
//				xListViewHeader.setVisibility(View.VISIBLE);
//				xListViewHeader.setState(2);
//				
//				mLocationClient.start();
//				if (mLocationClient != null && mLocationClient.isStarted())
//				mLocationClient.requestOfflineLocation();
				
				getContactList();
				break;
			default:
				mType = 0;
				ptrlv.onRefreshComplete();
				
				xListViewHeader.setState(0);
				xListViewHeader.setVisibility(View.GONE);
				break;
			}
		}

	};
	private void getContactList() {

		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
//				showLoadingDialog("正在加载,请稍后...");
				xListViewHeader.setShowText("正在加载,请稍候...");
				xListViewHeader.setVisibility(View.VISIBLE);
				xListViewHeader.setState(2);
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				initContactList();
				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
//				dismissLoadingDialog();
				xListViewHeader.setState(0);
				xListViewHeader.setVisibility(View.GONE);
				if (!result) {
					showCustomToast("数据加载失败...");
					mHandler2.sendEmptyMessage(3);
				} else {
					mHandler2.sendEmptyMessage(0);
				}
//				ptrstgv.getRefreshableView().hideFooterView();
			}

		});
	}
//	public void initContactList(){
//		if(BeemConnectivity.isConnected( mContext.getApplicationContext())){
//		    try {
//		    	if(mXmppFacade!=null){
//			    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
//							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
//							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
//			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()){
//			    		
//			    		mListGpsTemp = mXmppFacade.getGPSItems(StringUtils.parseName(mXmppFacade.getXmppConnectionAdapter().getJID()),
//			    				String.valueOf(mLongitude),
//			    				String.valueOf(mLatitude),
//			    				com.spice.im.utils.TextUtils.dateToMillis(new Date()),
//			    				mGpsAddr,//geolocation
//			    	    		mGenderSelect,
//			    	    		mAgeSelect,
//			    	    		mTimeSelect,
//			    				currentPage*numberresult,//startIndex
//			    				numberresult);//numResults
//			    		
////	//		    		if(mType==0){
////			    		TotalCount = mXmppFacade.getUserSearchCount(searchkey);
////						//总页码
////						pageCount = TotalCount%numberresult==0? TotalCount/numberresult-1 : TotalCount/numberresult;
////	//		    		}
////						Log.e("================20140713TotalCountpageCount(01)================", "TotalCount="+TotalCount+";pageCount="+pageCount);
////			    	    mListContactTemp = mXmppFacade.getUserSearch(searchkey,currentPage*numberresult,numberresult);
////			    	    if(mListContactTemp!=null && mListContactTemp.size()!=0)
//			    		if(mListGpsTemp!=null && mListGpsTemp.size()!=0){
//			    	    	errorType = 5;
//			    	    	gpsInfo = mListGpsTemp.get(0);
//			    	    	TotalCount = gpsInfo.getCttotal();
//			    	    	pageCount = TotalCount%numberresult==0? TotalCount/numberresult-1 : TotalCount/numberresult;
//			    	    	
//			    	    	ObjectCache.put("mListGpsTemp_"+mLogin+"_"+(currentPage*numberresult)+"_"+numberresult, mListGpsTemp,this);
//							ObjectCache.put("TotalCount_"+mLogin, TotalCount+"", this);
//							ObjectCache.put("pageCount_"+mLogin, pageCount+"", this);
//							ObjectCache.put("mGpsAddr_"+mLogin, mGpsAddr, this);
//							
//			    		}else{
//			    			if(mListGpsTemp!=null && mListGpsTemp.size()==0)
//			    				errorType = 0;
//			    			else
//			    				errorType = 6;
//			    		}
//						mChatManager = mXmppFacade.getChatManager();
//						mBinded = true;//20130804 added by allen
//			    	}else
//			    		errorType = 1;
//		    	}else
//		    		errorType = 2;
//				
//		    } catch (RemoteException e) {
//		    	errorType = 3;
//		    	e.printStackTrace();
//		    	
//		    } catch (Exception e){
//		    	errorType = 3;
//		    	e.printStackTrace();
//		    }
//	    }else{
//	    	errorType = 4;
//	    }
//	}
	
	
	public boolean initContactList(){
		if(BeemConnectivity.isConnected( getApplicationContext())){
		    try {
		    	if(mXmppFacade!=null){
			    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
			    			){
			    		
			    		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
			    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
			    	    
			    	    GpsIQ reqXML = new GpsIQ();
			            reqXML.setId("1234567890");
			            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
//			            reqXML.setUid(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
//			            reqXML.setUsername(username);
			            reqXML.setUsername(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));
			            reqXML.setLongitude(mLongitude+"");
			            reqXML.setLatitude(mLatitude+"");
			            String timeStr = com.spice.im.utils.TextUtils.dateToMillis(new Date());
			            reqXML.setTime(timeStr);
			            reqXML.setGeolocation(mGpsAddr);
			            reqXML.setGenderselect(mGenderSelect+"");
			            reqXML.setAgeselect(mAgeSelect+"");
			            reqXML.setTimeselect(mTimeSelect+"");
			            reqXML.setRadius(5000*1000+"");
			            reqXML.setStartIndex(currentPage*numberresult+"");
			            reqXML.setNumResults(numberresult+"");
			            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
//			            reqXML.setUuid(uuid);
//			            reqXML.setFuid(fuid);
//			            reqXML.setNote(note);
//			            reqXML.setOp("add");
//			            String hashcode = "";//apikey+uid+fuid 使用登录成功后返回的sessionid作为密码做3des运算
			            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+timeStr;
			            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
			            reqXML.setHashcode(hash_dest);
			            reqXML.setType(IQ.Type.SET);
			            String elementName = "gpsiq"; 
			    		String namespace = "com:stb:gpsiq";
			    		GpsIQResponseProvider provider = new GpsIQResponseProvider();
			            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "gpsiq", "com:stb:gpsiq", provider);
			            
			            if(rt!=null){
			                if (rt instanceof GpsIQResponse) {
			                	final GpsIQResponse gpsIQResponse = (GpsIQResponse) rt;

			                    if (gpsIQResponse.getChildElementXML().contains(
			                            "com:stb:gpsiq")) {
//			    					MainActivity.this.runOnUiThread(new Runnable() {
//				                    	
//            							@Override
//            							public void run() {
//            								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
//            							}
//            						});
			                        String Id = gpsIQResponse.getId();
			                        String Apikey = gpsIQResponse.getApikey();
			                        String recode = gpsIQResponse.getRetcode();
//			                        retcode = recode;
//			                        memo = friendAddIQResponse.getMemo();
			                        mListGpsTemp = gpsIQResponse.getUsers();
			                        
//			                        if(recode.equalsIgnoreCase("0000")){
//			                        	errorType = 5;
//				                        return true;
//			                        }else{
//			                        	errorType = 6;
//			                        	return false;
//			                        }
			                        if(mListGpsTemp!=null && mListGpsTemp.size()!=0){
						    	    	errorType = 5;
						    	    	gpsInfo = mListGpsTemp.get(0);
						    	    	try{
						    	    		TotalCount = Integer.parseInt(gpsIQResponse.getCttotal());
						    	    	}catch(Exception e){
						    	    		TotalCount = 0;
						    	    	}
						    	    	pageCount = TotalCount%numberresult==0? TotalCount/numberresult-1 : TotalCount/numberresult;
						    	    	
						    	    	ObjectCache.put("mListGpsTemp_"+mLogin+"_"+(currentPage*numberresult)+"_"+numberresult, mListGpsTemp,this);
										ObjectCache.put("TotalCount_"+mLogin, TotalCount+"", this);
										ObjectCache.put("pageCount_"+mLogin, pageCount+"", this);
										ObjectCache.put("mGpsAddr_"+mLogin, mGpsAddr, this);
										mChatManager = mXmppFacade.getChatManager();
										mBinded = true;//20130804 added by allen
										return true;
						    		}else{
						    			if(mListGpsTemp!=null && mListGpsTemp.size()==0){
						    				errorType = 0;
						    				mChatManager = mXmppFacade.getChatManager();
											mBinded = true;//20130804 added by allen
											return true;
						    			}else{
						    				errorType = 6;
						    				mChatManager = mXmppFacade.getChatManager();
											mBinded = true;//20130804 added by allen
											return false;
						    			}
						    		}
//									mChatManager = mXmppFacade.getChatManager();
			                        	
			                    }
			                } 
			            }
			    		
//						mBinded = true;//20130804 added by allen
			    	}else
			    		errorType = 1;
		    	}else
		    		errorType = 2;
				
		    } catch (RemoteException e) {
		    	errorType = 3;
		    	e.printStackTrace();
		    	
		    } catch (Exception e){
		    	errorType = 3;
		    	e.printStackTrace();
		    }
	    }else{
	    	errorType = 4;
	    }
		return false;
	}
    /**
     * Build and display the contact list.
     * @param group name of the contact list.
     * 根据群组号，构造群组用户列表
     * 初始化从平台获取用户列表时调用；同时选择按群类别显示时也调用
     */
    private void buildContactList() {//String group
    	
    	
    	
//		mListContact = mListContactTemp;
    	mListGps = mListGpsTemp;
//		Log.e("================20140713mListContact.size(02)================", "mListContact.size()="+mListContact.size());
		if(errorType==5 && mListGps!=null){
//    	if(mListGps!=null){
//			mSelectedGroup = group;
//			Log.d(TAG, "buildContactList for group " + group);
	
//			Log.e("================20130801================", "++++++++++++++AAAAmListContact.size()="+mListContact.size()+"+++++++++++++");
			
			
//			MultiUserChat multiUserChat = null;
//			if(col!=null && col.size()!=0){
//				BookmarkedConference bmc = null;
//				DuitangInfo info1 = null;
//				Iterator it = col.iterator();
//				while(it.hasNext()){
//					bmc = (BookmarkedConference)it.next();
////					System.out.println("※※※※※20130902PrivateData※※※※※===>name="+bmc.getName()+";isautojoin="+bmc.isAutoJoin()+";jid="+bmc.getJid()+";nick="+bmc.getNickname()+";password="+bmc.getPassword());
//		    		info1 = new DuitangInfo("1",bmc.getJid(),
//		    		60,60,"1733789",
//		    		bmc.getName()+"\n"+"群","");
//		    		info1.setName(bmc.getName()+"群");
//					if(mListContact!=null)
//						mListContact.add(new Contact(info1.getKey()));
//				}
//			}
			
//		    assignContactToGroups(mListContact, tmpGroupList);//mRoster.getContactList()
//		    makeSortedList(mContactOnGroup);
//		    mListContact = mContactOnGroup.get(group);
//			Collections.sort(mListContact);
//			mListContact = new SortedList<Contact>(mListContact, mComparator);
			
			DuitangInfo newsInfo1 = null;
//			Contact contact = null;
	        for (int i = 0; i < mListGps.size(); i++) {
	        	newsInfo1 = new DuitangInfo();
//	        	contact = (Contact)mListContact.get(i);
	        	gpsInfo = (XGpsInfo)mListGps.get(i);
	        	
	        	Log.e("MMMMMMMMMMMM20140714(2)MMMMMMMMMMMM", "++++++++++++++"+gpsInfo.toString()+"++++++++++++");
	        	
//	            newsInfo1.setKey(contact.getJIDWithRes());
	        	newsInfo1.setKey(gpsInfo.getUid());
	            newsInfo1.setAlbid("1733789");
//	            if(gpsInfo.getEmail()!=null 
//	            		&& gpsInfo.getEmail().length()!=0 
//	            		&& !gpsInfo.getEmail().equalsIgnoreCase("null")
//	            		&& (
//	            				gpsInfo.getEmail().toLowerCase().endsWith(".jpg")
//	            				|| gpsInfo.getEmail().toLowerCase().endsWith(".png")
//	            				|| gpsInfo.getEmail().toLowerCase().endsWith(".bmp")
//	            				|| gpsInfo.getEmail().toLowerCase().endsWith(".gif")
//	            			))
//	            newsInfo1.setIsrc(XmppConnectionAdapter.downloadPrefix+StringUtils.parseName(contact.getJIDWithRes())+"/"+"thumbnail_"+contact.getAvatarId());//contact.getAvatarId()
//	            	newsInfo1.setIsrc(XmppConnectionAdapter.downloadPrefix+StringUtils.parseName(gpsInfo.getJID())+"/"+gpsInfo.getEmail());//contact.getAvatarId()
	            newsInfo1.setIsrc(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+gpsInfo.getAvatarPath());
//	            showCustomToast("000gpsInfo.getAvatarPath()="+gpsInfo.getAvatarPath());
//	            showCustomToast("111newsInfo1.getIsrc()="+newsInfo1.getIsrc());
//	            if(gpsInfo.getJID().indexOf("@conference.")!=-1){
//	            	newsInfo1.setMsg(StringUtils.parseName(gpsInfo.getJID())+"\n"+"群");
//	            	newsInfo1.setName(StringUtils.parseName(gpsInfo.getJID())+"群");
//	            }else{
	            newsInfo1.setMsg(gpsInfo.getName()+"\n"+gpsInfo.getUid()+"@0");
	            newsInfo1.setName(gpsInfo.getName());
//	            }
	            if(uListype == 1){
	//            	newsInfo1.setHeight(newsInfoLeftObject.getInt("iht"));
	            	newsInfo1.setHeight(60);
	            	newsInfo1.setWidth(itemWidth);
	            }else if(uListype == 0){
	            	newsInfo1.setHeight(itemHeigth_listv);
	                newsInfo1.setWidth(itemWidth_listv);	
	            }
	            //20140808 start
//	            newsInfo1.setMstatus(gpsInfo.getStatus());
	            newsInfo1.setMuid(gpsInfo.getUid());
	            newsInfo1.setMdistance(gpsInfo.getDistance());
//	            newsInfo1.setMcttotal(gpsInfo.getCttotal());
	            newsInfo1.setTime(gpsInfo.getTime());
	            newsInfo1.setGender(gpsInfo.getGender());
	            newsInfo1.setBirthday(gpsInfo.getBirthday());
	            newsInfo1.setSign(gpsInfo.getUsersign());
	            //20140808 end
//	            Log.e("================20130801================", "++++++++++++++AAAAcontact.getAvatarId()="+contact.getAvatarId()+";contact.getName()="+contact.getName()+";contact.getMsgState()="+contact.getMsgState()+"+++++++++++++");
	            duitangs2.add(newsInfo1);
	        }
	        
	        if(duitangs2.size()!=0){
//		        if (actionType == 1) {
//		
//		            mAdapter.addItemTop(duitangs2);
//		            mAdapter.notifyDataSetChanged();
////		            mAdapterView.stopRefresh();
//		            duitangs2.clear();
//		            Log.e("================20130801================", "++++++++++++++GGGG");
//		        } else if (actionType == 2) {
//		            mAdapterView.stopLoadMore();
//		            mAdapter.addItemLast(duitangs2);
					if(mType == 2)
						mAdapter.addItemLast(duitangs2);
					else if(mType == 1)
						mAdapter.addItemTop(duitangs2);
					else
						mAdapter.addItemLast(duitangs2);
		            
		            mAdapter.notifyDataSetChanged();
//	                if(mType == 2)
//	                	ptrlv.getRefreshableView().setSelection(mAdapter.getCount()-1);
//	                else if(mType == 1)
//	                	ptrlv.getRefreshableView().setSelection(duitangs2.size()-1);
	                
//		            ptrlv.onRefreshComplete();

//		            if(ptrstgv.getCurrentMode()==Mode.BOTH 
//		            		|| ptrstgv.getCurrentMode()==Mode.PULL_FROM_END
//		            		|| ptrstgv.getCurrentMode()==Mode.MANUAL_REFRESH_ONLY)//showFooterLoadingLayout
//		            	;
//		            else if(ptrstgv.getCurrentMode()==Mode.PULL_FROM_START
//		            		|| ptrstgv.getCurrentMode()==Mode.BOTH)//showHeaderLoadingLayout
//		            	ptrstgv.getRefreshableView().hideFooterView();
//		            ptrstgv.onRefreshComplete();
		            duitangs2.clear();
//		            Log.e("================20130801================", "++++++++++++++HHHH");
//		        }
	        }else{
	//        	norecord.setText("暂无好友");
//	        	Toast.makeText(GpsSearchResPullRefListActivity.this,errorMsg[0], 1000).show();
	        	showCustomToast(errorMsg[0]);
	        }

		}else{
//			Toast.makeText(GpsSearchResPullRefListActivity.this,errorMsg[errorType], 1000).show();
			showCustomToast(errorMsg[errorType]);
		}
		mType = 0;
		ptrlv.onRefreshComplete();

    }


    protected List<AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();
	protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
		mAsyncTasks.add(asyncTask.executeOnExecutor(LIMITED_TASK_EXECUTOR, null));
	}

	protected void clearAsyncTask() {
		Iterator<AsyncTask<Void, Void, Boolean>> iterator = mAsyncTasks
				.iterator();
		while (iterator.hasNext()) {
			AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}
		mAsyncTasks.clear();
	}		    
//	protected void showLoadingDialog(String text) {
//		if (text != null) {
//			mLoadingDialog.setText(text);
//		}
//		mLoadingDialog.show();
//	}
//
//	protected void dismissLoadingDialog() {
//		if (mLoadingDialog.isShowing()) {
//			mLoadingDialog.dismiss();
//		}
//	}

	/** 显示自定义Toast提示(来自String) **/
	protected void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(GpsSearchResPullRefListActivity.this).inflate(
				R.layout.common_toast, null);
		((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(GpsSearchResPullRefListActivity.this);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
//	private boolean phonestate = false;//false其他， true接起电话或电话进行时 
//    /* 内部class继承PhoneStateListener */
//    public class exPhoneCallListener extends PhoneStateListener
//    {
//        /* 重写onCallStateChanged
//        当状态改变时改变myTextView1的文字及颜色 */
//        public void onCallStateChanged(int state, String incomingNumber)
//        {
//          switch (state)
//          {
//            /* 无任何状态时 :说明没有拨打电话的界面的时候，也就是在拨打电话前和挂电话后的情况*/
//            case TelephonyManager.CALL_STATE_IDLE:
//            	Log.e("================20131216 无任何电话状态时================", "无任何电话状态时");
//            	if(phonestate){
//            		onPhoneStateResume();
//            	}
//            	phonestate = false;
//              break;
//            /* 接起电话时 :至少有一个电话存在、拨出或激活、接听，而没有一个电话在通话或等待的状态*/
//            case TelephonyManager.CALL_STATE_OFFHOOK:
//            	Log.e("================20131216 接起电话时================", "接起电话时");
//            	onPhoneStatePause();
//            	phonestate = true;
//              break;
//            /* 电话进来时 :在通话的过程中*/
//            case TelephonyManager.CALL_STATE_RINGING:
////              getContactPeople(incomingNumber);
//            	Log.e("================20131216 电话进来时================", "电话进来时");
////            	onBackPressed();
//            	onPhoneStatePause();
//            	phonestate = true;
//              break;
//            default:
//              break;
//          }
//          super.onCallStateChanged(state, incomingNumber);
//        }
//    }
//    
//    protected void onPhoneStatePause() {
////		super.onPause();
//    	try{
//		try {
//		    if (mRoster != null) {
//			mRoster.removeRosterListener(mBeemRosterListener);
//			mRoster = null;
//		    }
//		} catch (RemoteException e) {
//		    Log.d("ContactList", "Remote exception", e);
//		}
//		if (mBinded) {
//			getApplicationContext().unbindService(mServConn);
//		    mBinded = false;
//		}
//		mXmppFacade = null;
//    	}catch(Exception e){
//    		e.printStackTrace();
//    	}
//    }
//    
//    protected void onPhoneStateResume() {
////		super.onResume();
//    	try{
//		if (!mBinded){
////		    new Thread()
////		    {
////		        @Override
////		        public void run()
////		        {
//		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);
//
////		        }
////		    }.start();		    
//		}
//		if (mBinded){
//	        Intent intent = getIntent(); 
//	        //0普通图片listview 1瀑布流  2地图模式
//	        uListype = intent.getIntExtra("uListypefor", (int) 0);  
//	        roomname = intent.getStringExtra("roomname");
//	        Log.e("================20130804uListype resume1================", "++++++++++++++ContactlistWithPop uListype="+uListype);
//	        mImageFetcher.setUListype(uListype);
//	        mImageFetcher.setExitTasksEarly(false);
//	        ptrlv.setAdapter(mAdapter);
////	        AddItemToContainer(currentPage, 2 ,duitangs2);
//		}
//    	}catch(Exception e){
//    		e.printStackTrace();
//    	}
//    }
//	@Override
//	public void connectionStatusChanged(int connectedState, String reason) {
//		Log.e("MMMMM20140604MMMMMMMMMMMM", "++++++++++++++connectionStatusChanged0++++++++++++");
//		switch (connectedState) {
//		case 0://connectionClosed
//			mHandler3.sendEmptyMessage(0);
//			break;
//		case 1://connectionClosedOnError
////			mConnectErrorView.setVisibility(View.VISIBLE);
////			mNetErrorView.setVisibility(View.VISIBLE);
////			mConnect_status_info.setText("连接异常!");
//			mHandler3.sendEmptyMessage(1);
//			break;
//		case 2://reconnectingIn
////			mNetErrorView.setVisibility(View.VISIBLE);
////			mConnect_status_info.setText("连接中...");
//			mHandler3.sendEmptyMessage(2);
//			break;
//		case 3://reconnectionFailed
////			mNetErrorView.setVisibility(View.VISIBLE);
////			mConnect_status_info.setText("重连失败!");
//			mHandler3.sendEmptyMessage(3);
//			break;
//		case 4://reconnectionSuccessful
////			mNetErrorView.setVisibility(View.GONE);
//			mHandler3.sendEmptyMessage(4);
//
//		default:
//			break;
//		}
//	}
//	Handler mHandler3 = new Handler() {
//
//		@Override
//		public void handleMessage(android.os.Message msg) {
//			super.handleMessage(msg);
//			switch (msg.what) {
//			case 0:
//				break;
//
//			case 1:
//				mNetErrorView.setVisibility(View.VISIBLE);
//				if(BeemConnectivity.isConnected(mContext))
//				mConnect_status_info.setText("连接异常!");
//				break;
//
//			case 2:
//				mNetErrorView.setVisibility(View.VISIBLE);
//				if(BeemConnectivity.isConnected(mContext))
//				mConnect_status_info.setText("连接中...");
//				break;
//			case 3:
//				mNetErrorView.setVisibility(View.VISIBLE);
//				if(BeemConnectivity.isConnected(mContext))
//				mConnect_status_info.setText("重连失败!");
//				break;
//			case 4:
//				mNetErrorView.setVisibility(View.GONE);
//				break;
//			case 5:
//				mNetErrorView.setVisibility(View.VISIBLE);
//				mConnect_status_info.setText("当前网络不可用，请检查你的网络设置。");
//				break;
//			}
//		}
//
//	};
//	private BroadcastReceiver mNetWorkReceiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            String action = intent.getAction();  
//            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {  
//                Log.d("PoupWindowContactList", "网络状态已经改变");  
////                connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
////                info = connectivityManager.getActiveNetworkInfo();    
////                if(info != null && info.isAvailable()) {  
////                    String name = info.getTypeName();  
////                    Log.d(tag, "当前网络名称：" + name);  
////                    //doSomething()  
////                } else {  
////                    Log.d(tag, "没有可用网络");  
////                  //doSomething()  
////                }  
//                if(BeemConnectivity.isConnected(context)){
////                	mNetErrorView.setVisibility(View.GONE);
////                	isconnect = 0;
//                	mHandler3.sendEmptyMessage(4);
//                }else{
////                	mNetErrorView.setVisibility(View.VISIBLE);
////                	isconnect = 1;
//                	mHandler3.sendEmptyMessage(5);
//                	Log.d("PoupWindowContactList", "当前网络不可用，请检查你的网络设置。");
//                }
//            } 
//        }
//	};
	
	private class OnRightImageButtonClickListener implements
	onRightImageButtonClickListener {
	
		@Override
		public void onClick() {
			startActivity(new Intent(GpsSearchResPullRefListActivity.this, ContactFrameActivity.class));//ContactListPullRefListActivity
			GpsSearchResPullRefListActivity.this.finish();
		}
	}
	protected class OnMiddleImageButtonClickListener implements
	onMiddleImageButtonClickListener {

		@Override
		public void onClick() {
//			if (isSelect) {
				mPopupWindow
						.showViewTopCenter(findViewById(R.id.layout_right));
//			} else {
//				mPopupWindow.dismiss();
//			}
		}
	}
	private void initPopupWindow() {
		mPopupWindow = new NearByPopupWindow(this,this);
		mPopupWindow.setOnSubmitClickListener(new onSubmitClickListener() {

			@Override
			public void onClick() {
//				mPeopleFragment.onManualRefresh();
			}
		});
		mPopupWindow.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
//				mHeaderSpinner.initSpinnerState(false);
			}
		});
		mPopupWindow.registerGpsFilterCallback(GpsSearchResPullRefListActivity.this);
	}
	//0全部 1男 2女
	private int mGenderSelect = 0;
    //不限(0),16–22岁(1),23–30岁(2),31岁以上(3)</item>
	private int mAgeSelect = 0;
	//0 不限,1 15分钟,2 60分钟,3 3天
	private int mTimeSelect = 0;
	@Override
	public void gpsFilterChanged(int GenderSelect,int AgeSelect,int TimeSelect) {
		mGenderSelect = GenderSelect;
		mAgeSelect = AgeSelect;
		mTimeSelect = TimeSelect;
		mHandler2.sendEmptyMessage(10);
	}
//	@Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data1) {
//    	
//    	super.onActivityResult(requestCode, resultCode, data1);
//    	if (resultCode != RESULT_OK) return;
//    	switch (requestCode) {
//    		case 1:
//    			Intent intent = getIntent();
//    			int GenderSelect = intent.getIntExtra("GenderSelect", 0);
//    			int AgeSelect = intent.getIntExtra("AgeSelect", 0);
//    			int TimeSelect = intent.getIntExtra("TimeSelect", 0);
//    			//showCustomToast("GenderSelect="+GenderSelect+";AgeSelect="+AgeSelect+";TimeSelect="+TimeSelect);
//    			Toast.makeText(this, "GenderSelect="+GenderSelect+";AgeSelect="+AgeSelect+";TimeSelect="+TimeSelect, Toast.LENGTH_LONG);
//    			break;
//    		
//    	}
//	}
	
	private String[] errorMsg = new String[]{"抱歉,没有找到相关结果.",
			"服务连接中1-1,请稍候再试.",
			"服务连接中1-2,请稍候再试.",
			"服务连接中1-3,请稍候再试.",
			"网络连接不可用,请检查你的网络设置.",
			"",
			"请求异常,稍候重试!"};
	private int errorType = 5;
	
	public void preLoad(){//联网前先显示缓存内容
		Object obj3 = ObjectCache.get("mListGpsTemp_"+mLogin+"_"+(currentPage*numberresult)+"_"+numberresult,this);
		if(obj3!=null){
			mListGpsTemp = (List)obj3;
		}else
			Log.d(TAG, "get of memory cache key = "+"mtmpGroupList_"+(currentPage*numberresult)+"_"+numberresult+"is null");
		try{
			Object obj5 = ObjectCache.get("TotalCount_"+mLogin, this);
			if(obj5!=null)
				TotalCount = Integer.parseInt((String)obj5);
			Object obj6 = ObjectCache.get("pageCount_"+mLogin, this);
			if(obj6!=null)
				pageCount = Integer.parseInt((String)obj6);
		}catch(Exception e){}
		Object obj4 = ObjectCache.get("mGpsAddr_"+mLogin, this);
		if(obj4!=null){
			mGpsAddr = (String)obj4;
			mHeaderLayout.setDefaultTitle("附近", mGpsAddr);
		}
		
	}
	
	
    //百度定位start
	public LocationClient mLocationClient;
	public LocationClientOption option;
//	public GeofenceClient mGeofenceClient;
	public MyLocationListener mMyLocationListener;
	public double mLongitude;
	public double mLatitude;
	public String mGpsAddr;
	/**
	 * 实现定位回调监听
	 */
	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			int result = 9;
			//Receive Location 
			if(location==null){
//				dismissLoadingDialog();
				xListViewHeader.setState(0);
				xListViewHeader.setVisibility(View.GONE);
				showCustomToast("定位失败...");
				return;
			}if(location!=null
					&&location.getLongitude()!=0.0
					&& location.getLatitude()!=0.0
					&& location.getAddrStr()!=null){
				result = 8;
			mLongitude = location.getLongitude();
			mLatitude = location.getLatitude();
			mGpsAddr = location.getAddrStr();
			SpiceApplication.getInstance().mLongitude = mLongitude;
			SpiceApplication.getInstance().mLatitude = mLatitude;
			SpiceApplication.getInstance().mGpsAddr = mGpsAddr;
			Log.e("※※※※※※20140725地理位置※※※※※※", "※※※※※※经度:" + mLongitude + ",纬度:" + mLatitude + ",地址:" + mGpsAddr);
			
			StringBuffer sb = new StringBuffer(256);
			sb.append("time : ");
			sb.append(location.getTime());
			sb.append("\nerror code : ");
			sb.append(location.getLocType());
			sb.append("\nlatitude : ");
			sb.append(location.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(location.getLongitude());
			sb.append("\nradius : ");
			sb.append(location.getRadius());
			if (location.getLocType() == BDLocation.TypeGpsLocation){
				sb.append("\nspeed : ");
				sb.append(location.getSpeed());
				sb.append("\nsatellite : ");
				sb.append(location.getSatelliteNumber());
				sb.append("\ndirection : ");
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
				sb.append(location.getDirection());
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation){
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
				//运营商信息
				sb.append("\noperationers : ");
				sb.append(location.getOperators());
			}
			Log.e("※※※※※※20140725BaiduLocationApiDem※※※※※※", sb.toString());
			}
			mHandler2.sendEmptyMessage(result);
			mLocationClient.stop();
			
		}
	}
	private void InitLocation(){
		option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);//设置定位模式Hight_Accuracy,Battery_Saving,Device_Sensors
		option.setOpenGps(true);
		
		option.setCoorType("bd09ll");//返回的定位结果是百度经纬度，默认值gcj02,bd09ll,bd09
		option.setScanSpan(5000);//设置发起定位请求的间隔时间为5000ms
		option.setIsNeedAddress(true);//返回的定位结果包含地址信息
		mLocationClient.setLocOption(option);
	}
    //百度定位end
	
	/**20140806 格式转换开始start*/
//	List<Contact> mListContactTempNew = new ArrayList<Contact>();
	List<XGpsInfo> mListGpsTempNew = new ArrayList<XGpsInfo>();
	public List<XGpsInfo> convertDuitangInfos2ListContact(LinkedList<DuitangInfo> mInfos){
		mListGpsTempNew.clear();
		DuitangInfo newsInfo1 = null;
		XGpsInfo contact = null;
		if(mInfos!=null)
	        for (int i = 0; i < mInfos.size(); i++) {
	        	newsInfo1 = (DuitangInfo)mInfos.get(i);
//	        	contact = new GpsInfo(newsInfo1.getKey());
//	        	contact.setAvatarId(newsInfo1.getIsrc());
//	        	contact.setName(newsInfo1.getName());
//	        	contact.setGender(newsInfo1.getGender());
//	        	contact.setBirthday(newsInfo1.getBirthday());
//	        	contact.setSign(newsInfo1.getSign());
	        	contact = new XGpsInfo();
//	        	contact.setStatus(newsInfo1.getMstatus());
	        	contact.setName(newsInfo1.getName());
	        	contact.setUid(newsInfo1.getMuid());
	        	contact.setEmail(newsInfo1.getIsrc());
	        	contact.setDistance(newsInfo1.getMdistance());
//	        	contact.setCttotal(newsInfo1.getMcttotal());
	        	contact.setUsersign(newsInfo1.getSign());
	        	contact.setAvatarPath(newsInfo1.getIsrc());
	        	mListGpsTempNew.add(contact);
	        }
		return mListGpsTempNew;
	}
	/**20140806格式转换结束end*/
	
	
	//网络状态 start
		@Override
		public void connectionStatusChanged(int connectedState, String reason) {
			Log.e("MMMMM20140604MMMMMMMMMMMM", "++++++++++++++connectionStatusChanged0++++++++++++");
			switch (connectedState) {
			case 0://connectionClosed
				mHandler3.sendEmptyMessage(0);
				break;
			case 1://connectionClosedOnError
//				mConnectErrorView.setVisibility(View.VISIBLE);
//				mNetErrorView.setVisibility(View.VISIBLE);
//				mConnect_status_info.setText("连接异常!");
				mHandler3.sendEmptyMessage(1);
				break;
			case 2://reconnectingIn
//				mNetErrorView.setVisibility(View.VISIBLE);
//				mConnect_status_info.setText("连接中...");
				mHandler3.sendEmptyMessage(2);
				break;
			case 3://reconnectionFailed
//				mNetErrorView.setVisibility(View.VISIBLE);
//				mConnect_status_info.setText("重连失败!");
				mHandler3.sendEmptyMessage(3);
				break;
			case 4://reconnectionSuccessful
//				mNetErrorView.setVisibility(View.GONE);
				mHandler3.sendEmptyMessage(4);

			default:
				break;
			}
		}
		Handler mHandler3 = new Handler() {

			@Override
			public void handleMessage(android.os.Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case 0:
					break;

				case 1:
					mNetErrorView.setVisibility(View.VISIBLE);
					if(BeemConnectivity.isConnected(mContext))
					mConnect_status_info.setText("连接异常!");
					break;

				case 2:
					mNetErrorView.setVisibility(View.VISIBLE);
					if(BeemConnectivity.isConnected(mContext))
					mConnect_status_info.setText("连接中...");
					break;
				case 3:
					mNetErrorView.setVisibility(View.VISIBLE);
					if(BeemConnectivity.isConnected(mContext))
					mConnect_status_info.setText("重连失败!");
					break;
					
				case 4:
					mNetErrorView.setVisibility(View.GONE);
					String udid = "";
					String partnerid = "";
					try{
						udid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().UDID;
						partnerid = mXmppFacade.getXmppConnectionAdapter().getMService().getPartnerid();
					}catch(Exception e){
						e.printStackTrace();
					}
//					udidTextView.setText("udid="+udid);
//					partneridEditText.setText(partnerid);
//					getContactList();//20141025 added by allen
					break;
				case 5:
					mNetErrorView.setVisibility(View.VISIBLE);
					mConnect_status_info.setText("当前网络不可用，请检查你的网络设置。");
					break;
				case 6:
					if(mXmppFacade!=null 
//							&& mXmppFacade.getXmppConnectionAdapter()!=null 
//							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
							&& BeemConnectivity.isConnected(mContext)){
						
					}else{
						mNetErrorView.setVisibility(View.VISIBLE);
						if(BeemConnectivity.isConnected(mContext))
						mConnect_status_info.setText("网络可用,连接中...");
					}
					break;	
				}
			}

		};
		private BroadcastReceiver mNetWorkReceiver = new BroadcastReceiver() {
	        @Override
	        public void onReceive(Context context, Intent intent) {
	            String action = intent.getAction();  
	            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {  
	                Log.d("PoupWindowContactList", "网络状态已经改变");  
//	                connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
//	                info = connectivityManager.getActiveNetworkInfo();    
//	                if(info != null && info.isAvailable()) {  
//	                    String name = info.getTypeName();  
//	                    Log.d(tag, "当前网络名称：" + name);  
//	                    //doSomething()  
//	                } else {  
//	                    Log.d(tag, "没有可用网络");  
//	                  //doSomething()  
//	                }  
	                if(BeemConnectivity.isConnected(context)){
//	                	mNetErrorView.setVisibility(View.GONE);
//	                	isconnect = 0;
	                	mHandler3.sendEmptyMessage(6);//4
	                }else{
//	                	mNetErrorView.setVisibility(View.VISIBLE);
//	                	isconnect = 1;
	                	mHandler3.sendEmptyMessage(5);
	                	Log.d("PoupWindowContactList", "当前网络不可用，请检查你的网络设置。");
	                }
	            } 
	        }
		};
		
		private boolean phonestate = false;//false其他， true接起电话或电话进行时 
	    /* 内部class继承PhoneStateListener */
	    public class exPhoneCallListener extends PhoneStateListener
	    {
	        /* 重写onCallStateChanged
	        当状态改变时改变myTextView1的文字及颜色 */
	        public void onCallStateChanged(int state, String incomingNumber)
	        {
	          switch (state)
	          {
	            /* 无任何状态时 :说明没有拨打电话的界面的时候，也就是在拨打电话前和挂电话后的情况*/
	            case TelephonyManager.CALL_STATE_IDLE:
	            	Log.e("================20131216 无任何电话状态时================", "无任何电话状态时");
	            	if(phonestate){
	            		onPhoneStateResume();
	            	}
	            	phonestate = false;
	              break;
	            /* 接起电话时 :至少有一个电话存在、拨出或激活、接听，而没有一个电话在通话或等待的状态*/
	            case TelephonyManager.CALL_STATE_OFFHOOK:
	            	Log.e("================20131216 接起电话时================", "接起电话时");
	            	onPhoneStatePause();
	            	phonestate = true;
	              break;
	            /* 电话进来时 :在通话的过程中*/
	            case TelephonyManager.CALL_STATE_RINGING:
//	              getContactPeople(incomingNumber);
	            	Log.e("================20131216 电话进来时================", "电话进来时");
//	            	onBackPressed();
	            	onPhoneStatePause();
	            	phonestate = true;
	              break;
	            default:
	              break;
	          }
	          super.onCallStateChanged(state, incomingNumber);
	        }
	    }
	    
	    protected void onPhoneStatePause() {
//			super.onPause();
	    	try{
//	    		try {
//	    		    if (mRoster != null) {
//	    			mRoster.removeRosterListener(mBeemRosterListener);
//	    			mRoster = null;
//	    		    }
//	    		} catch (RemoteException e) {
//	    		    Log.d("ContactList", "Remote exception", e);
//	    		}
				if (mBinded) {
					getApplicationContext().unbindService(mServConn);
				    mBinded = false;
				}
				mXmppFacade = null;
	    	}catch(Exception e){
	    		e.printStackTrace();
	    	}
	    }
	    
	    protected void onPhoneStateResume() {
//			super.onResume();
	    	try{
			if (!mBinded){
//			    new Thread()
//			    {
//			        @Override
//			        public void run()
//			        {
			    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);

//			        }
//			    }.start();		    
			}
			if (mBinded){
				mImageFetcher.setExitTasksEarly(false);
			}
	    	}catch(Exception e){
	    		e.printStackTrace();
	    	}
	    }
	    
	    /*
	     * 打开设置网络界面
	     * */
	    public static void setNetworkMethod(final Context context){
	        //提示对话框
	        AlertDialog.Builder builder=new AlertDialog.Builder(context);
	        builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {
	            
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	                // TODO Auto-generated method stub
	                Intent intent=null;
	                //判断手机系统的版本  即API大于10 就是3.0或以上版本 
	                if(android.os.Build.VERSION.SDK_INT>10){
	                    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
	                }else{
	                    intent = new Intent();
	                    ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
	                    intent.setComponent(component);
	                    intent.setAction("android.intent.action.VIEW");
	                }
	                context.startActivity(intent);
	            }
	        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
	            
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	                // TODO Auto-generated method stub
	                dialog.dismiss();
	            }
	        }).show();
	    }
		//网络状态 end
	
}
